//
//  FBtMessageModel.m
//  JwPackDemo
//
//  Created by 陈警卫 on 2025/8/14.
//

#import "FBtMessageModel.h"
#import "JwPackDemo-Swift.h"
#import "FBtManager.h"

@interface FBtMessageModel ()

/// 超时计时器
@property (nonatomic, strong) NSTimer *timer;
/// 重复次数计次
@property (nonatomic, assign) NSInteger echoIndex;

/// 超时回调
@property (nonatomic, copy) void(^didTimeoutAction)(FBtMessageModel *messageModel);

@end

@implementation FBtMessageModel

- (void)dealloc {
    NSLog(@"%@--dealloc", self);
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupData];
        [self setupNoti];
    }
    return self;
}

- (void)setupData {
    self.signal = FBtSig_init;
    self.timeout = 3;
    self.echo = 0;
    self.state = FBtMessageStateInit;
    self.level = FBtMessageLevelPlain;
    self.writeType = FBtMessageWriteTypeWithoutResponse;
}

- (void)setupNoti {
    
}

/// 配置完整数据
- (void)setupCompleData {
    
    if (!self.prefix) {
        self.prefix = 0x7F7F;
    }
    if (!self.suffix) {
        self.suffix = 0xF7F7;
    }
    UInt16 prefix = self.prefix;
    UInt16 suffix = self.suffix;
    NSData *prefixData = [NSData dataWithBytes:&prefix length:sizeof(prefix)];
    NSData *suffixData = [NSData dataWithBytes:&suffix length:sizeof(suffix)];
    
    UInt8 func = self.func;
    UInt8 type = self.type;
    UInt16 length = self.length;
    
    if (self.value) {
        length = self.value.length;
    }
    if (self.signal) {
        func = (self.signal >> 8) & 0xFF;
        type = self.signal & 0xFF;
        
        if (type != 0x00) {
            length = self.length + 1;
        }
    }
    
    self.stamp = [NSDate f_packetIDData];
    
    UInt16 length_r = CFSwapInt16HostToBig(length);
    NSData *lengthData = [NSData dataWithBytes:&length_r length:sizeof(length_r)];
    
    NSData *funcData = [NSData dataWithBytes:&func length:sizeof(func)];
    NSData *typeData = [NSData dataWithBytes:&type length:sizeof(type)];
    
    NSMutableData *messageData = [NSMutableData data];
    [messageData appendData:prefixData];
    [messageData appendData:funcData];
    [messageData appendData:self.stamp];
    [messageData appendData:lengthData];
    if (type != 0x00) {
        [messageData appendData:typeData];
    }
    [messageData appendData:self.value];
    
    NSData *crcRawData = [messageData subdataWithRange:(NSMakeRange(2, messageData.length - 2))];
    UInt16 crc = [CJCRCHub computeCRC16WithData:crcRawData type:(CJCRC16TypeModbus)];
    NSData *crcData = [NSData dataWithBytes:&crc length:sizeof(crc)];
    [messageData appendData:crcData];
    [messageData appendData:suffixData];
    
    self.data = messageData;
    self.key = [self.stamp f_hexString];
}

- (void)endTimer {
    [self.timer invalidate];
    self.timer = nil;
}

/// 启动计时器
- (void)startTimerWithAction:(void(^)(FBtMessageModel *messageModel))action {
    if (self.timeout > 0) {
        self.didTimeoutAction = action;
        [self endTimer];
        __weak typeof(self) wself = self;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timeout repeats:NO block:^(NSTimer * _Nonnull timer) {
            // 可强引用保活此类(暂时不用)
            [wself timeoutAction];
        }];
    }
}

- (void)timeoutAction {
    if (self.state == FBtMessageStateSended) {
        if (self.echo > 0 && self.echo > self.echoIndex) {
            [self send];
            self.echoIndex += 1;
        } else {
            self.state = FBtMessageStateTimeout;
            if (self.didTimeoutAction) {
                self.didTimeoutAction(self);
            }
        }
    }
}

/// 发送数据
- (FBtMessageModel *)send {
    // 发送数据
    [[FBtManager shared].btSession sendWithMessageModel:self];
    return self;
    
}



@end
